<template>
  <div class="app-container">
    <!-- 上部分表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      label-position="center"
      class="globalSerchFormStyle"
      style="margin: 10px 0px"
    >
      <el-row>
        <el-col :span="6" v-if="$store.state.user.userLevel == null">
          <el-form-item
            label="油企名称"
            prop="enterpriseName"
            size="small"
            style="padding-top: 4px"
          >
            <el-select
              v-model="queryParams.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企"
              @change="handleSelectChange"
              style="width: 190px"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="$store.state.user.userLevel != 2">
          <el-form-item
            label="油站名称"
            prop="stationName"
            size="small"
            style="padding-top: 4px"
          >
            <el-select
              v-model="queryParams.stationId"
              :clearable="true"
              filterable
              placeholder="请选择油站"
              style="width: 190px"
            >
              <el-option
                v-for="(item, index) in stationIdList"
                :key="index"
                :value="item.stationId"
                :label="item.stationName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="油罐名称"
            prop="oilOmeterName"
            clearable
            size="small"
            style="padding-top: 4px"
          >
            <el-input
              v-model="queryParams.oilOmeterName"
              placeholder="请输入油罐名称"
              style="width: 190px"
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="油品"
            prop="oilName"
            clearable
            size="small"
            style="padding-top: 4px"
          >
            <el-select
              v-model="queryParams.oilId"
              :clearable="true"
              filterable
              placeholder="请选择油品"
              style="width: 190px"
            >
              <el-option
                v-for="(item, index) in oilList"
                :key="index"
                :label="item.oilName"
                :value="item.oilId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="button-from"></div>
    </el-form>
    <el-row class="global_el_rowStyle" :gutter="10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
          size="mini"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
          plain
          >重置</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          @click="handleExport"
          size="mini"
          plain
          >导出</el-button
        ></el-col
      > -->
      <!-- <el-col :span="1.5">
        <el-button
          v-show="delIds.length"
          icon="el-icon-delete"
          @click="handleDeleteAll"
          size="mini"
          plain
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table style="width: 100%" :data="tankList" stripe v-loading="loading">
      <af-table-column
        label="油企名称"
        align="left"
        prop="enterpriseName"
        v-if="$store.state.user.userLevel == null"
        width="200px"
      />
      <af-table-column
        width="200px"
        label="油站名称"
        align="left"
        prop="stationName"
      />
      <af-table-column
        width="200px"
        label="油罐名称"
        align="left"
        prop="oilOmeterName"
      />
      <af-table-column label="油品" align="left" prop="oilName" />

      <af-table-column label="油高(mm)" align="left" prop="oilHight">
        <template slot-scope="{ row }">
          {{ row.oilHight && row.oilHight.toFixed(2) }}
        </template>
      </af-table-column>
      <af-table-column label="水高(mm)" align="left" prop="waterHight">
        <template slot-scope="{ row }">
          {{ row.waterHight && row.waterHight.toFixed(2) }}
        </template>
      </af-table-column>
      <af-table-column label="数量(L/kg)" align="left" prop="ometerCapacity">
        <template slot-scope="{ row }">
          {{ row.ometerCapacity && row.ometerCapacity.toFixed(2) }}
        </template>
      </af-table-column>
      <af-table-column label="温度(℃)" align="left" prop="temperature">
        <template slot-scope="{ row }">
          {{ row.temperature && row.temperature + "℃ " }}</template
        >
      </af-table-column>
      <af-table-column label="关联油枪" align="left" prop="ometerGunNum" />

      <af-table-column
        fixed="right"
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
        width="200px"
      >
        <!--fixed="right"-->
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            disable
            @click="handleEdit(scope.row)"
            >编辑油罐</el-button
          >

          <el-button size="mini" type="text" @click="handleDel(scope.row)"
            >删除</el-button
          >
        </template>
      </af-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="page.pageNum"
      :limit.sync="page.pageSize"
      @pagination="getList"
    />

    <!-- 编辑和新增的抽屉 -->

    <el-drawer
      :title="title"
      :visible.sync="showDrawer"
      :before-close="sortingCancel"
      custom-class="add-drawer"
    >
      <div style="overflow: auto">
        <el-form
          style="padding: 0 20px 0 20px"
          ref="sortingForm"
          :model="sortingForm"
          label-position="top"
          :rules="rules"
        >
          <el-form-item
            label="油企名称"
            prop="enterpriseId"
            v-if="$store.state.user.userLevel == null"
            style="padding-bottom: 10px"
          >
            <el-select
              :disabled="isEdit == true"
              v-model="sortingForm.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企"
              @change="handleSelectChange"
              style="width: 100%; padding-top: 10px"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>

          <div
            v-if="stationIdList.length == 1"
            style="font-size: 14px; color: #000000a9; font-weight: 400"
          >
            油站名称： {{ stationIdList[0].stationName }}
          </div>
          <div
            v-else-if="$store.state.user.userLevel == '2'"
            style="font-size: 14px; color: #000000a9; font-weight: 400"
          >
            油站名称： {{ $store.state.user.presentStationName }}
          </div>

          <el-form-item
            v-else
            label="油站名称"
            prop="stationId"
            key="stationId"
            style="padding-bottom: 10px"
          >
            <el-select
              :disabled="isEdit == true"
              v-model="sortingForm.stationId"
              :clearable="true"
              filterable
              placeholder="请选择油站"
              @change="getGun"
              style="width: 100%; padding-top: 10px"
            >
              <el-option
                v-for="(item, index) in stationIdList"
                :key="index"
                :value="item.stationId"
                :label="item.stationName"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            label="油罐名"
            prop="oilOmeterName"
            style="padding-bottom: 10px"
          >
            <el-input
              v-model="sortingForm.oilOmeterName"
              placeholder="请输入油罐名"
              style="padding-top: 10px"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item
            label="油枪"
            prop="ometerGunNum"
            style="padding-bottom: 10px"
          >
            <el-select
              v-model="sortingForm.ometerGunNum"
              :clearable="true"
              filterable
              multiple
              placeholder="请选择油枪"
              style="width: 100%; padding-top: 10px"
            >
              <el-option
                v-for="(item, index) in oilGunList"
                :key="index"
                :value="item.gunNum"
                :label="`${item.gunNum}-${item.oilName}-${item.oilClass}-${item.oilType}  `"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-col :span="12">
            <el-form-item
              label="罐高(mm)"
              prop="ometerHight"
              style="padding-bottom: 10px"
            >
              <el-input
                style="padding-top: 10px; padding-right: 10px"
                v-model="sortingForm.ometerHight"
                placeholder="请输入罐高"
                maxlength="15"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="最大容量(L)"
              prop="ometerCapacity"
              style="padding-bottom: 10px"
            >
              <el-input
                style="padding-top: 10px"
                v-model="sortingForm.ometerCapacity"
                placeholder="请输入最大容量"
                maxlength="15"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="油品高度(mm)"
              prop="oilHight"
              style="padding-bottom: 10px"
            >
              <el-input
                style="padding-top: 10px; padding-right: 10px"
                v-model="sortingForm.oilHight"
                placeholder="请输入油品高度"
                maxlength="15"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="水位高度(mm)"
              prop="waterHight"
              style="padding-bottom: 10px"
            >
              <el-input
                style="padding-top: 10px"
                v-model="sortingForm.waterHight"
                placeholder="请输入水位高度"
                maxlength="15"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="油品"
              prop="oilId"
              style="padding-bottom: 10px"
            >
              <el-select
                v-model="sortingForm.oilId"
                :clearable="true"
                filterable
                placeholder="请选择油品"
                style="width: 100%; padding-top: 10px; padding-right: 10px"
              >
                <el-option
                  v-for="(item, index) in currentOilList"
                  :key="index"
                  :value="item.oilId"
                  :label="item.oilName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="温度(℃)"
              prop="temperature"
              style="padding-bottom: 10px"
            >
              <el-input
                v-model="sortingForm.temperature"
                style="padding-top: 10px"
                placeholder="请填写温度"
                maxlength="15"
              />
            </el-form-item>
          </el-col>
        </el-form>
        <div class="fr" style="margin: 20px">
          <el-button type="primary" size="mini" @click="sortingSubmitForm"
            >确 定</el-button
          >
          <el-button size="mini" @click="sortingCancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { cloneDeep } from "lodash";
import { listEnterpriseStation, getEnterpriseList } from "@/api/dept";
import {
  listInfo,
  delOmeter,
  updateOmeter,
  addOmeter,
  getStationGun,
  getOilList,
} from "@/api/station/tank";
export default {
  name: "Oil_Tank",
  data() {
    // 保留2小数 ，只能输入数字
    let validatorSorting = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        value = String(value);
        let end = Number(value.trim());
        let pattern;
        let start;

        pattern = /^\d+(\.\d{1,2})?$/; //  两位小数点
        start = this.queryParams.startAmt;

        if (Number.isNaN(end)) return callback(new Error("请输入有效数值"));
        if (end <= 0) return callback(new Error("不能小于等于0"));
        if (!pattern.test(end)) return callback(new Error("最多两位小数点"));
        console.log(start, end);
        callback();
      }
      console.log("rule", rule);
    };

    return {
      // 查询参数
      page: {
        pageNum: 1,
        pageSize: 10,
      },
      queryParams: {},
      enterpriseList: [], //油企列表
      stationIdList: [], // 油站列表
      oilGunList: [], // 油枪列表
      oilList: [], // 油品列表
      currentOilList: [], //
      total: 0, //列表页数
      tankList: [], //列表数组
      loading: false, //加载
      currentGun: "", // 通过油站获取 油枪
      // 表单校验
      rules: {
        enterpriseId: [
          { required: true, message: "请选择油企名称", trigger: "change" },
        ],

        oilId: [{ required: true, message: "请选择油品", trigger: "change" }],

        ometerGunNum: [
          {
            type: "array",
            required: true,
            message: "请选择油枪",
            trigger: "submit",
          },
        ],
        oilOmeterName: [
          { required: true, message: "请输入油罐名", trigger: "blur" },
        ],
        temperature: [{ validator: validatorSorting, trigger: "change" }],
        waterHight: [{ validator: validatorSorting, trigger: "change" }],
        oilHight: [{ validator: validatorSorting, trigger: "change" }],
        ometerCapacity: [{ validator: validatorSorting, trigger: "change" }],
        ometerHight: [{ validator: validatorSorting, trigger: "change" }],
        stationId: [
          {
            required: true,
            message: "请选择油站名称",
            trigger: "change, blur",
          },
        ],
      },
      // 新增和编辑抽屉
      showDrawer: false,
      title: "", // 抽屉标题
      // 新增表单参数
      sortingForm: {},
      isEdit: false, //判断是否是编辑抽屉
      delVisible: false, //删除提示
    };
  },
  watch: {
    async currentGun(val) {
      if (val) {
        this.sortingForm.stationId = val;
        const res = await getStationGun(val);
        console.log(res, "currentGun");
        this.oilGunList = res.data;
      }
    },
  },
  async created() {
    // admin 可以设置 所有权限油罐 ，油企 油站 油枪 油品相互关联
    this.userLevel = this.$store.state.user.userLevel;
    this.enterpriseId =
      this.$store.state.user.presentEnterprise &&
      this.$store.state.user.presentEnterprise.enterpriseId;
    this.stationId = this.$store.state.user.stationId;
    // 油企权限 需要拉去名下油站和油品
    if (this.userLevel === "1") {
      this.getStationListQuery(this.enterpriseId);
      const res = await getOilList({
        enterpriseId: this.enterpriseId,
      });
      this.oilList = res.data;
      this.queryParams.enterpriseId = this.enterpriseId;
    } else if (this.userLevel === null) {
      // admin权限 全部获取
      this.getEnterpriseListQuery();
      const res = await getOilList({});
      this.oilList = res.data;
    } else if (this.userLevel === "2") {
      const res = await getOilList({
        stationId: this.stationId,
      });
      this.oilList = res.data;
      this.queryParams.stationId = this.stationId;
      // 油站时，不再动态监听 直接获取油枪
      const res2 = await getStationGun(this.stationId);
      this.oilGunList = res2.data;
    }
    this.getList();
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true;
      const res = await listInfo(this.page, this.queryParams);
      this.tankList = res.rows;
      this.total = res.total;
      this.loading = false;
    },
    // 改变切换油企时
    handleSelectChange(val) {
      this.sortingForm.stationId = null;
      this.getStationListQuery(val);
    },
    // 查询油企
    getEnterpriseListQuery() {
      getEnterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 查询 油站列表
    getStationListQuery(val) {
      listEnterpriseStation({ enterpriseId: val }).then(async (res) => {
        this.stationIdList = res;
        // 判断是多站还是单站 --单站
        if (this.stationIdList.length == 1) {
          this.currentGun = this.stationIdList[0].stationId;
          // 如果 单站 直接 查名下油品
          const res = await getOilList({
            stationId: this.stationIdList[0].stationId,
          });
          this.currentOilList = res.data;
        }
      });
    },
    // 下拉框选中时 为多站
    async getGun(val) {
      // 油枪
      this.currentGun = this.sortingForm.stationId;
      console.log(this.currentGun, "===");
      // 油品
      const res = await getOilList({ stationId: val });
      this.currentOilList = res.data;
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.userLevel === "1") {
        this.queryParams = {
          enterpriseId: this.enterpriseId,
        };
      } else if (this.userLevel === "2") {
        this.queryParams = {
          stationId: this.stationId,
        };
      } else {
        this.queryParams = {};
      }
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.resetForm("sortingForm");
      this.sortingForm = {};
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.title = "新增油罐";
      this.isEdit = false;
      this.sortingForm = {};
      this.currentOilList = [];
      if (this.userLevel == "2") {
        const res = await getOilList({ stationId: this.stationId });
        this.currentOilList = res.data;
      }
      if (this.userLevel === null) {
        this.stationIdList = [];
      }
      this.showDrawer = true;
      this.reset();
    },
    // 删除按钮
    handleDel(row) {
      console.log(row, "删除");
      this.$confirm(`确认删除此油罐“${row.oilOmeterName}”吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delOmeter(row.ometerId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除油罐成功");
        });
    },
    // 编辑按钮
    async handleEdit(row) {
      this.title = "编辑油罐";
      this.isEdit = true;
      this.currentOilList = [];
      const res = await getOilList({ stationId: row.stationId });
      this.currentOilList = res.data;
      const editData = JSON.parse(JSON.stringify(row));
      editData.ometerGunNum = editData.ometerGunNum.split(",");
      const res2 = await getStationGun(editData.stationId);
      console.log(res2, "res2");
      this.oilGunList = res2.data;

      this.sortingForm = editData;
      this.getStationListQuery(this.sortingForm.enterpriseId);
      this.showDrawer = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },

    // 保存
    sortingSubmitForm() {
      this.$refs.sortingForm.validate(async (valid) => {
        if (valid) {
          let res;
          if (this.userLevel === "1" || this.userLevel === "2") {
            // 在油企时需要传入油站id
            this.sortingForm.enterpriseId = this.enterpriseId;
          }
          if (this.userLevel === "2") {
            this.sortingForm.stationId = this.stationId;
          }
          const editData = cloneDeep(this.sortingForm);
          editData.ometerGunNum = editData.ometerGunNum.join(",");
          if (this.isEdit) {
            res = await updateOmeter(editData);
          } else {
            res = await addOmeter(editData);
          }
          if (res && res.code === 200) {
            this.getList();
            this.$message.success(res.msg);
            this.$refs["sortingForm"].resetFields();

            this.showDrawer = false;
          } else {
            this.$message.error(res.msg);
          }
        }
      });
    },
    // 关闭抽屉
    sortingCancel() {
      this.$refs["sortingForm"].resetFields();
      this.reset();
      this.showDrawer = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  margin-top: -15px;
  ::v-deep .el-drawer {
    overflow: auto;
    overflow-y: auto;
  }
}

.button-from {
  width: 100%;
  display: flex;
  flex-wrap: wrap;

  .button-style1 {
    display: inline-block;
    width: 80px;

    .el-button {
      margin: 0 0 0 15px;
    }
  }
}

::v-deep .card-table {
  padding: 10px;
  margin-top: 0 !important;
  background-color: #f8f8f8;

  .el-button {
    margin: 0 5px 0 0;
  }
}

// 表格样式
::v-deep .el-form-item {
  margin-bottom: 0;

  .el-form-item__label {
    padding: 0;
    margin: 0;
    height: 29px;
    font-weight: 400;
    font-size: 12px;
    text-align: center;
  }

  .el-button--cyan {
    margin-center: 20px;
  }
}

::v-deep .el-table {
  border: 1px #f8f8f8 solid;
  border-bottom: 1px #dfe6ec solid;
}

::v-deep .is-center {
  border: 1px transparent solid;
  border-bottom: 1px #f8f8f8 solid;
}

.summary-container {
  width: 100%;
  border: 1px solid #e7e3e3;
  padding: 10px 5px;
  border-radius: 10px;
  // display: grid;
  // grid-template-columns: repeat(5, 1fr);
  // grid-template-rows: repeat(3, 80px);
  margin-bottom: 14px;

  display: flex;
  flex-direction: row;

  .summary-item {
    // height: 240px;
    display: flex;
    flex-direction: column;

    // width: 100%;
    // height: 100%;
    // display: flex;
    // justify-items: center;
    // align-items: center;
    // flex-direction: column;
    border-right: 1px dashed rgba(0, 0, 0, 0.1);

    .summary-item-box {
      border-bottom: 1px dashed rgba(0, 0, 0, 0.1);
      padding: 5px;
      display: flex;
      justify-items: center;
      align-items: center;
      flex-direction: column;

      .summary-title {
        font-size: 18px;
      }

      .summary-sum {
        font-size: 24px;
        font-weight: 700;
      }
    }
  }

  .summary-item:last-child {
    border-right: none;
  }

  .summary-item-box:nth-last-child(-n + 1) {
    border-bottom: none;
  }
}

.f1 {
  flex: 1;
}
.add-drawer {
  overflow-y: auto;
}

.el-drawer__wrapper {
  overflow-y: auto;
}
</style>
